package testing.domain.question.yaml;

import testing.domain.err.FileProblemException;
import testing.domain.question.Question;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QuestionSerializer {
   // public ArrayList<Question> questions;
    Map<Question,Integer> questionMap;
    int questionKey;
    public QuestionSerializer(){
         this.questionMap = new LinkedHashMap<Question, Integer>();

        questionKey = 0;
    }
  //  public QuestionSerializer(ArrayList<Question> questions) {
  //      this.questions = questions;
  //  }
    public QuestionAdd serializeQuestion (String text) throws FileProblemException {
    if(text == null)
        throw new FileProblemException("Where is non null File?!");
        HashMap<Integer, Question> idQuestionMap = new HashMap<Integer, Question>();
        Pattern questionPattern = Pattern.compile("!testing.domain.question.Question\\s*(\\d+?)\\s*name:([^\n]*)\n" +
                "rightAnswer:([^\n]*)\\s*answers:\\[(.*)\\]\\s*");
        Matcher matcher = questionPattern.matcher(text);
        while (matcher.find())
        {
            int num = Integer.valueOf(matcher.group(1));
            System.out.println("The num of question : "+num);
            String name = matcher.group(2);
            System.out.println(name);
            String rightAnswer = matcher.group(3);
            System.out.println("Answer is : "+rightAnswer);
            String[] answers = matcher.group(4).trim().split(", ");
            for (int i=0;i<answers.length;i++)
            {
                System.out.print(answers[i]+" | ");
            }
            System.out.println("\n************************");
            Question ques = new Question(name,rightAnswer,answers);
            idQuestionMap.put(num,ques);
        }
                QuestionAdd questionSerialize = new QuestionAdd(new ArrayList<Question>(idQuestionMap.values()));
        return questionSerialize;
    }
    private void serialize(Question ques,FileWriter writer) throws IOException {
       if(!questionMap.containsKey(ques))
       {
           String questionTemplate = String.format(
                   "\n\n---\n!testing.domain.question.Question %d\nname:%s\nrightAnswer:%s\nanswers:%s",
                   questionKey, ques.getName(), ques.getRightAnswer(), Arrays.toString(ques.getAnswers()));
           writer.write(questionTemplate);
           questionMap.put(ques,questionKey++);
       }
    }
    public void serializeAll(QuestionAdd questionSerialize,FileWriter writer) throws IOException {
        for(Question ques:questionSerialize.questions)
            serialize(ques,writer);
    }
}
